﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Interactivity;
using Microsoft.Expression.Interactivity.Layout;

namespace DragDrop
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void ball_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            Canvas source = null;
            Canvas dest = null;
            double top = 0;

            if(this.cSource.Children.Contains(ball))
            {
                source = cSource;
                dest = cDest;
            }
            else
            {
                source = cDest;
                dest = cSource;
                top = 480;
            }

            Rect rectDest = UserControlBounds(dest, top);
    
            BehaviorCollection behaviours = Interaction.GetBehaviors(ball);

            if (behaviours.Count > 0 && behaviours[0] is MouseDragElementBehavior)
            {
                MouseDragElementBehavior dragBehaviour = behaviours[0] as MouseDragElementBehavior;

                Rect temp = new Rect(dragBehaviour.X, dragBehaviour.Y, ball.ActualWidth, ball.ActualHeight);

                temp.Intersect(rectDest);

                if (temp != Rect.Empty)
                {
                    //// intersection so make it a child.
                    source.Children.Remove(ball);

                    ball.RenderTransform = new MatrixTransform();
                    dest.Children.Add(ball);
                }
            }
        }

        private Rect UserControlBounds(FrameworkElement element, double top)
        {
            return new Rect(element.Margin.Left, top, element.ActualWidth, element.ActualHeight);
        }
    }
}